<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <script src="../../assets/iconfont.js"></script>
    <link rel="stylesheet" href="../../assets/css/common.css" />
    <link rel="stylesheet" href="../../assets/element-ui/index.css" />
    <link rel="stylesheet" href="./index.min.css" />
    <title>图像编辑器</title>
</head>

<body>
    <div id="app" class="plant-t-img-editor">
        <el-container class="main-content">
            <el-header>
                <div class="params-box">
                    <div class="main selector-rate"
                        v-if="childActiveMark=='CROP-SELECT-YOURSELF'&&btnActiveMark=='crop'">
                        宽：<input style="width:20px;" v-model.number="cropRateW" />
                        高：<input style="width:20px;" v-model.number="cropRateH" />
                    </div>
                    <div class="main passport-paper"
                        v-if="childActiveMark=='PASSPORT-PAPER-TYPE'&&btnActiveMark=='passport'">
                        纸张：
                        <el-select v-model="passportPaper" placeholder="请选择纸张规格" @change="handlePassportPaperChange"
                            style="width:180px;height:20px !important;">
                            <el-option v-for="item in paperTypes" :key="item.name"
                                :label="`${item.name} 【${item.size[0]}cm,${item.size[0]}cm】`" :value="item.name">
                            </el-option>
                        </el-select>
                    </div>
                    <div class="main passport-count"
                        v-if="childActiveMark=='PASSPORT-IMAGE-COUNT'&&btnActiveMark=='passport'">
                        数量：<input style="width:20px;" v-model.number="passportCount" />
                        页边距(垂直)：<input style="width:20px;" v-model.number="passportColPageBorder" />
                        <br />
                        页边距(水平)：<input style="width:20px;" v-model.number="passportRowPageBorder" />
                        照片边距：<input style="width:20px;" v-model.number="passportBorder" />
                    </div>
                </div>
                <div class="childbtns" v-if="btnActiveMark">
                    <div class="btn" :class="{'active':childActiveMark == item.mark}"
                        v-for="item,index in btnChildren[btnActiveMark]" :key="item.mark"
                        @click="handleChildBtnClick(item.mark)"
                        :style="(index==0?'border-top:solid 2px #c2c2c2;':'')+(index==btnList.length-1?'border-bottom:solid 2px #c2c2c2;':'')+('color:'+item.color??'#fff'+'unset;')">
                        <i :class="item.icon"></i>
                        <div>{{item.name}}</div>
                    </div>
                </div>
            </el-header>
            <el-container>
                <el-main id="container">
                    <el-upload v-show="!imageData" action="" class="upload-image" drag accept=".jpg,.jpeg,.png,.bmp"
                        :show-file-list="false" :before-upload="handleImageLoad">
                        <i class="el-icon-picture-outline"></i>
                        <div class="el-upload__text">将图片文件拖到此处，或<em>点击选择</em></div>
                    </el-upload>
                    <canvas ref="image-board" :width="canvasBlock.rw" :height="canvasBlock.rh"
                        :style="{width:`${canvasBlock.w}px`,height:`${canvasBlock.h}px`}"></canvas>
                </el-main>
                <el-aside class="tools" width="70px">
                    <div class="btn" :class="{'active':btnActiveMark==item.mark}" v-for="item,index in btnList"
                        @click="handleBtnClick(item.mark)"
                        :style="(index==0?'border-top:solid 2px #c2c2c2;':'')+(index==btnList.length-1?'border-bottom:solid 2px #c2c2c2;':'')">
                        <i :class="item.icon"></i>
                        <div>{{item.name}}</div>
                    </div>
                </el-aside>
            </el-container>
        </el-container>
        <el-dialog title="修改分辨率" :visible.sync="showResolution" width="30%" :close-on-click-modal="false">
            <el-form ref="resolutionForm" :model="resolutionForm" label-width="40px">
                <el-form-item label="宽">
                    <el-input v-model="resolutionForm.w" @input="e=>handleResolutionInput('w',e)"
                        placeholder="请输入分辨率宽度"></el-input>
                </el-form-item>
                <el-form-item label="高">
                    <el-input v-model="resolutionForm.h" @input="e=>handleResolutionInput('h',e)"
                        placeholder="请输入分辨率高度"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="showResolution = false">取 消</el-button>
                <el-button type="primary" @click="handleEditResolution">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog title="打印设置" :visible.sync="showPrintPad" width="500px">
            <div style="padding-bottom:50px;">*照片排版功能不需要设置页边距，否则尺寸会有误差。</div>
            <el-form ref="printerForm" :model="printerForm" label-width="80px">
                <el-form-item label="打印机">
                    <el-select v-model="printerForm.printerName" placeholder="请选择打印机">
                        <el-option v-for="item in printerList" :key="item.name" :label="item.name" :value="item.name">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="纸张规格">
                    <el-select v-model="printerForm.paperType" placeholder="请选择纸张规格">
                        <el-option v-for="item in paperTypes" :key="item.name" :label="item.name" :value="item.name">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="页边距">
                    <el-select v-model="printerForm.border" placeholder="请选择页边距">
                        <el-option label="无" :value="0"></el-option>
                        <el-option label="小" :value="1"></el-option>
                        <el-option label="大" :value="2"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="showPrintPad = false">取 消</el-button>
                <el-button type="primary" @click="()=>handlePrint(true)">预览</el-button>
                <el-button type="primary" @click="()=>handlePrint()">打印</el-button>
            </span>
        </el-dialog>
        <div class="loading-screen" v-show="loading">
            <i class="el-icon-loading"></i>
        </div>
    </div>
</body>
<script src="../../assets/js/vue2.js"></script>
<script src="../../assets/element-ui/index.js"></script>
<script src="../../assets/element-ui/et.js"></script>
<script src="./assets/utils.js"></script>
<script>
    Vue.config.productionTip = true
    new Vue({
        el: '#app',
        data: {
            loading: false,
            plugins: new Plugins(),
            //canvas的绘制属性
            canvasBlock: {
                w: 0,
                h: 0,
                rw: 0,
                rh: 0,
                scale: 1,
                rotate: 0,
                image: false
            },
            //图像数据
            imageData: undefined,
            //框选的起点坐标
            selectStart: undefined,
            //框选的基于canvas的最终坐标组
            cropLocation: undefined,
            //是否鼠标左键按下状态
            isMouseLeftDown: false,
            //活跃的按钮
            childActiveMark: undefined,
            //子按钮
            btnChildren: {
                crop: [
                    {
                        icon: 'el-icon-mouse',
                        name: '自由比例',
                        mark: 'CROP-SELECT-FREEDOM'
                    },
                    {
                        icon: 'el-icon-full-screen',
                        name: '1：1',
                        mark: 'CROP-SELECT-SQUARE'
                    },
                    {
                        icon: 'el-icon-tickets',
                        name: '2寸照片',
                        mark: 'CROP-SELECT-TWO-INCH'
                    },
                    {
                        icon: 'el-icon-tickets',
                        name: '1寸照片',
                        mark: 'CROP-SELECT-ONE-INCH'
                    },
                    {
                        icon: 'el-icon-setting',
                        name: '自设比例',
                        mark: 'CROP-SELECT-YOURSELF'
                    },
                    {
                        icon: 'el-icon-scissors',
                        name: '裁剪',
                        mark: 'CROP-SURE',
                        color: '#99CC66'
                    },
                    {
                        icon: 'el-icon-error',
                        name: '关闭',
                        mark: 'CROP-CANCEL'
                    }
                ],
                passport: [
                    {
                        icon: 'el-icon-document',
                        name: '纸张规格',
                        mark: 'PASSPORT-PAPER-TYPE'
                    },
                    {
                        icon: 'el-icon-film',
                        name: '排版数量',
                        mark: 'PASSPORT-IMAGE-COUNT'
                    },
                    {
                        icon: 'el-icon-folder-delete',
                        name: '撤销排版',
                        mark: 'PASSPORT-CANCEL',
                    },
                    {
                        icon: 'el-icon-check',
                        name: '排版',
                        mark: 'PASSPORT-START',
                        color: '#99CC66'
                    },
                    {
                        icon: 'el-icon-error',
                        name: '关闭',
                        mark: 'PASSPORT-CLOSE'
                    }
                ]
            },
            //活跃的按钮
            btnActiveMark: undefined,
            //按钮
            btnList: [
                {
                    icon: 'el-icon-refresh-right',
                    name: '旋转90度',
                    mark: 'rotate'
                },
                {
                    icon: 'el-icon-reading',
                    name: '镜像',
                    mark: 'image'
                },
                {
                    icon: 'el-icon-crop',
                    name: '裁剪',
                    mark: 'crop'
                },
                {
                    icon: 'el-icon-user',
                    name: '寸照排版',
                    mark: 'passport'
                },
                {
                    icon: 'el-icon-monitor',
                    name: '分辨率',
                    mark: 'resolution'
                },
                // {
                //     icon: 'el-icon-notebook-2',
                //     name: 'OCR',
                //     mark: 'ocr'
                // },
                // {
                //     icon: 'el-icon-search',
                //     name: '二维码',
                //     mark: 'erm'
                // },
                {
                    icon: 'el-icon-printer',
                    name: '打印',
                    mark: 'print'
                },
                {
                    icon: 'el-icon-delete-solid',
                    name: '清除',
                    mark: 'clear'
                },
                {
                    icon: 'el-icon-folder-checked',
                    name: '保存',
                    mark: 'save'
                }
            ],
            cropRateW: 1,
            cropRateH: 1,
            passportCount: 0,
            passportPaper: 'A4',
            paperTypes: [
                { name: 'A4', size: [21, 29.7] },
                { name: 'A5', size: [14.8, 21] },
                { name: 'A6', size: [10.5, 14.8] }
            ],
            passportRowPageBorder: 1,//纸张边宽
            passportColPageBorder: 1,
            passportBorder: 0.4,//相片边宽
            passportImageCache: undefined,
            imageDataHistory: [],
            showResolution: false,//是否显示调整分辨率的模态框
            resolutionForm: {
                w: undefined,
                h: undefined
            },
            //printPad
            showPrintPad: false,
            printerForm: { preview: false, imagePath: undefined, printerName: undefined, paperType: 'A4', border: 0 },
            printerList: [],
            fileName: undefined
        },
        created() {
            window.addEventListener("DOMContentLoaded", () => {
                window.$.onIpc('printers', (e, printers) => {
                    this.showPrintPad = true
                    this.printerList = printers
                    const defaultPrinter = printers.find(e => e.isDefault)
                    this.printerForm.printerName = defaultPrinter.name
                    this.printerForm.iw = this.canvasBlock.w
                    this.printerForm.ih = this.canvasBlock.h
                    this.loading = false
                })
                window.$.onIpc('printerFilePath', (e, path) => {
                    this.printerForm.imagePath = path
                    this.loading = false
                })
            });
        },
        mounted() {
            //监听并自适应element窗口
            window.addEventListener("resize", (e) => {
                this.$nextTick(_ => {
                    if (this.imageData) {
                        this.drawContent()
                    }
                })
            })
        },
        watch: {
            btnActiveMark(n, o) {
                //监听btnActiveMark属性，做一些清除功能缓存的事情
                switch (o) {
                    case 'passport':
                        this.passportImageCache = undefined
                        break
                    case 'crop':
                        this.clearSelectRect()
                        break
                    default:
                        break
                }
                this.childActiveMark = undefined
            }
        },
        methods: {
            //dom监听
            //监听裁剪时鼠标按下
            listenCropMouseDown(event) {
                const canvas = this.$refs['image-board']
                const rate = this.canvasBlock.rw / this.canvasBlock.w
                //储存起点坐标
                //判断x
                const cx = event.clientX - canvas.offsetLeft
                const x = cx > 0 ? (cx > canvas.width ? canvas.width : cx) : 0
                //判断y
                const cy = event.clientY - canvas.offsetTop - 80 + 1
                const y = cy > 0 ? (cy > canvas.height ? canvas.height : cy) : 0
                this.selectStart = [x * rate, y * rate]
                this.isMouseLeftDown = true
            },
            //监听裁剪时按下后移动
            async listenCropMouseMove(event) {
                if (!this.selectStart) return
                if (!this.isMouseLeftDown) return
                const canvas = this.$refs['image-board']
                const ctx = canvas.getContext('2d')
                const [sx, sy] = this.selectStart
                let nowMouseX = 0
                let nowMouseY = 0
                const rate = this.canvasBlock.rw / this.canvasBlock.w
                const cx = (event.clientX - canvas.offsetLeft) * rate
                const cy = (event.clientY - canvas.offsetTop - 80 + 1) * rate
                //内部方法:按照比例框选 r 宽高比
                const calcRateXY = (r) => {
                    nowMouseX = cx
                    if (cy > sy) {
                        nowMouseY = sy + Math.abs(nowMouseX - sx) / r
                    } else {
                        nowMouseY = sy - Math.abs(nowMouseX - sx) / r
                    }
                    var maxMouseX = canvas.width
                    var maxMouseY = canvas.height
                    if (nowMouseX > maxMouseX || nowMouseX < 0) {
                        return false
                    }
                    if (nowMouseY > maxMouseY || nowMouseY < 0) {
                        return false
                    }
                    return true
                }
                switch (this.childActiveMark) {
                    case 'CROP-SELECT-FREEDOM':
                        nowMouseX = cx > 0 ? (cx > canvas.width ? canvas.width : cx) : 0
                        nowMouseY = cy > 0 ? (cy > canvas.height ? canvas.height : cy) : 0
                        break
                    case 'CROP-SELECT-SQUARE':
                        if (!calcRateXY(1)) return
                        break
                    case 'CROP-SELECT-TWO-INCH':
                        if (!calcRateXY(3.5 / 4.5)) return
                        break
                    case 'CROP-SELECT-ONE-INCH':
                        if (!calcRateXY(2.5 / 3.5)) return
                        break
                    case 'CROP-SELECT-YOURSELF':
                        if (!calcRateXY(this.cropRateW / this.cropRateH)) return
                        break
                }
                ctx.clearRect(0, 0, canvas.width, canvas.height);//先清空
                await this.drawContent()
                //计算路径，先按不规则
                ctx.beginPath()
                ctx.moveTo(sx, sy);
                ctx.lineTo(sx, nowMouseY);
                ctx.lineTo(nowMouseX, nowMouseY);
                ctx.lineTo(nowMouseX, sy);
                ctx.lineTo(sx, sy);
                ctx.closePath();
                ctx.setLineDash([5 * rate, 5 * rate]);
                ctx.lineWidth = 2 * rate;
                ctx.strokeStyle = '#CCFF66';
                ctx.shadowColor = '#330099'; // 阴影颜色
                ctx.shadowBlur = 3;       // 阴影模糊度
                ctx.shadowOffsetX = 2;     // 阴影水平偏移量
                ctx.shadowOffsetY = 2;
                ctx.stroke();
                //储存截图坐标点【topX,topY,bottomX,bottomY】
                this.cropLocation = [Math.min(this.selectStart[0], nowMouseX), Math.min(this.selectStart[1], nowMouseY), Math.max(this.selectStart[0], nowMouseX), Math.max(this.selectStart[1], nowMouseY)]
            },
            //监听裁剪时鼠标松开
            ListenCropMouseUpOrLeave() {
                this.isMouseLeftDown = false
            },
            /*========================================>( 通用方法 )<========================================*/
            //计算排版纸张属性
            calcPassportPaperAttr() {
                const canvas = this.$refs['image-board']
                const { width, height } = canvas
                const iamgeRate = (width / height).toFixed(2) //图像比例
                let imgInchs = undefined //图像尺寸
                if (iamgeRate == 0.71) {
                    imgInchs = [2.5, 3.5]
                }
                if (iamgeRate == 0.78) {
                    imgInchs = [3.5, 4.5]
                }
                if (!imgInchs) return
                const paperwh = this.paperTypes.find(e => e.name == this.passportPaper).size //预设纸张尺寸
                //计算图像的行数和排数
                const paperBoxWidth = paperwh[0] - this.passportRowPageBorder * 2
                const paperBoxHeight = paperwh[1] - this.passportColPageBorder * 2
                const passportBoxWidth = imgInchs[0] + this.passportBorder
                const passportBoxHeight = imgInchs[1] + this.passportBorder
                const rowPassportCount = Math.floor(paperBoxWidth / passportBoxWidth)
                const colPassportCount = Math.floor(paperBoxHeight / passportBoxHeight)
                const passportCount = rowPassportCount * colPassportCount
                return {
                    paperwh,
                    imgInchs,
                    paperBoxWidth,
                    paperBoxHeight,
                    passportBoxWidth,
                    passportBoxHeight,
                    rowPassportCount,
                    colPassportCount,
                    passportCount
                }
            },
            clearSelectRect() {
                const canvas = this.$refs['image-board']
                document.removeEventListener('mousedown', this.listenCropMouseDown)
                document.removeEventListener('mousemove', this.listenCropMouseMove)
                document.removeEventListener('mouseup', this.ListenCropMouseUpOrLeave)
                this.cropLocation = undefined
                this.imageDataHistory = []
            },
            resetCanvasBlock() {
                this.canvasBlock = {
                    w: 0,
                    h: 0,
                    rw: 0,
                    rh: 0,
                    scale: 1,
                    rotate: 0,
                    image: false
                }
            },

            //阻断图片上传，并初始化图形
            handleImageLoad(file) {
                this.loading = true
                console.log('文件类型', file)
                this.fileName = file.name
                const allowTypes = ['image/jpeg', 'image/png', 'image/bmp', 'bmp']
                const isLt20M = file.size / 1024 / 1024 < 20;
                if (allowTypes.indexOf(file.type) == -1) {
                    this.plugins.alertError('图片格式不支持')
                    return false
                }
                if (!isLt20M) {
                    this.plugins.alertError('图片大小不能超过 10MB!')
                    return false
                }
                setTimeout(async () => {
                    this.imageData = await this.getImageFromFile(file)
                    await this.drawContent()
                    this.loading = false
                }, 50)

                return false
            },
            //根据canvasBlock绘制canvas,并且fit父框
            //TODO 简化父框计算宽高
            drawContent() {
                return new Promise(resolve => {
                    let width, height //canvas的宽高
                    const canvas = this.$refs['image-board']
                    ctx = canvas.getContext('2d')
                    const { scale, rotate, image } = this.canvasBlock
                    const container = document.getElementById('container')//获取父框宽高
                    //根据父框的宽高，计算出合适的canvas宽高，以达到canvas适应屏幕
                    const containerWidth = Math.floor(container.offsetWidth * 0.95)
                    const containerHeight = Math.floor(container.offsetHeight * 0.95)
                    const imgWidth = (rotate % 2 == 0 ? this.imageData.width : this.imageData.height)
                    const imgHeight = (rotate % 2 == 0 ? this.imageData.height : this.imageData.width)
                    //计算fit
                    const containerRate = containerWidth / containerHeight
                    const imgRate = imgWidth / imgHeight
                    if (containerRate >= imgRate) {
                        height = containerHeight
                        width = Math.floor(height * imgRate)

                    } else {
                        width = containerWidth
                        height = Math.floor(width / imgRate)
                    }
                    this.canvasBlock.w = width
                    this.canvasBlock.h = height
                    this.canvasBlock.rw = imgWidth
                    this.canvasBlock.rh = imgHeight

                    //开始绘画，如果发生了旋转，则旋转过后重新绘制canvas
                    this.$nextTick(_ => {
                        const angle = (Math.PI / 2) * rotate
                        ctx.rotate(angle)
                        ctx.save();
                        switch (rotate) {
                            case 0:
                                if (image) {
                                    ctx.translate(imgWidth, 0)
                                    ctx.scale(-1, 1);
                                }
                                ctx.drawImage(this.imageData, 0, 0, imgWidth, imgHeight);
                                break
                            case 1:
                                if (image) {
                                    ctx.translate(imgHeight, 0);
                                    ctx.scale(-1, 1);
                                }
                                ctx.drawImage(this.imageData, 0, -imgWidth, imgHeight, imgWidth);
                                break
                            case 2:
                                if (image) {
                                    ctx.translate(-imgWidth, 0);
                                    ctx.scale(-1, 1);
                                }
                                ctx.drawImage(this.imageData, -imgWidth, -imgHeight, imgWidth, imgHeight);
                                break
                            case 3:
                                if (image) {
                                    ctx.translate(-imgHeight, 0);
                                    ctx.scale(-1, 1);
                                }
                                ctx.drawImage(this.imageData, -imgHeight, 0, imgHeight, imgWidth);
                                break
                        }
                        ctx.restore();
                        ctx.rotate(-angle)
                        resolve()
                    })
                })
            },
            getImageFromFile(file) {
                return new Promise(resolve => {
                    const reader = new FileReader();
                    reader.onload = function (e) {
                        const base64 = e.target.result;
                        // 在这里使用base64，例如可以将其设置到图片的src属性
                        const image = new Image()
                        image.src = base64
                        image.onload = () => {
                            resolve(image)
                        }
                    };
                    reader.readAsDataURL(file); // 读取文件并转换为Base64
                })
            },
            getImageFromBase64(base64) {
                return new Promise(resolve => {
                    // 在这里使用base64，例如可以将其设置到图片的src属性
                    const image = new Image()
                    image.src = base64
                    image.onload = () => {
                        resolve(image)
                    }
                })
            },
            drawBox() {
                // ctx.strokeRect(100, 100, 100, 100)
                console.log('asdasdasdasd')
            },
            async handleBtnClick(mark) {
                if (!this.imageData || this.btnActiveMark == mark) {
                    return
                }
                this.btnActiveMark = undefined
                switch (mark) {
                    case 'rotate':
                        this.canvasBlock.rotate = (this.canvasBlock.rotate == 3 ? 0 : this.canvasBlock.rotate + 1)
                        await this.drawContent()
                        break
                    case 'image':
                        this.canvasBlock.image = !this.canvasBlock.image
                        await this.drawContent()
                        break
                    case 'crop':
                        this.btnActiveMark = mark
                        break
                    case 'passport':
                        //寸照排版，先判断图像是不是1寸或2寸照片
                        const attr = this.calcPassportPaperAttr()
                        if (!attr) {
                            this.plugins.alertError('请先将图像裁剪成寸照大小')
                            return
                        }
                        const { passportCount } = attr
                        this.passportCount = passportCount
                        this.btnActiveMark = mark

                        setTimeout(async () => {
                            var canvas = this.$refs['image-board']
                            this.passportImageCache = await this.getImageFromBase64(canvas.toDataURL("image/png"))
                        }, 50)

                        break
                    case 'resolution':
                        this.showResolution = true
                        this.resolutionForm = {
                            w: this.imageData.width,
                            h: this.imageData.height
                        }
                        break
                    case 'print':
                        this.loading = true
                        window.$.sendIpc('main-pad-get-printers')
                        var canvas = this.$refs['image-board']
                        var data = canvas.toDataURL("image/jpeg")
                        window.$.sendIpc('main-pad-cache-save', { defaultPath: this.fileName, data })
                        break
                    case 'clear':
                        this.clearSelectRect()
                        this.resetCanvasBlock()
                        this.imageData = undefined
                        this.plugins.msgSuccess('清除成功')
                        break
                    case 'save':
                        await this.drawContent()
                        var canvas = this.$refs['image-board']
                        var data = canvas.toDataURL("image/jpeg")
                        window.$.sendIpc('main-pad-file-save', { title: '选择图像保存位置', defaultPath: `PLanB制图${new Date().getTime()}.jpg`, data })
                        break
                    default:
                        break
                }
            },
            async handleChildBtnClick(mark) {
                // console.log('handleChildBtnClick', mark)
                if (this.childActiveMark == mark) return
                switch (mark) {
                    case 'CROP-SELECT-FREEDOM':
                    case 'CROP-SELECT-SQUARE':
                    case 'CROP-SELECT-TWO-INCH':
                    case 'CROP-SELECT-ONE-INCH':
                    case 'CROP-SELECT-YOURSELF':
                        this.childActiveMark = mark
                        this.clearSelectRect()
                        document.addEventListener('mousedown', this.listenCropMouseDown)
                        document.addEventListener('mousemove', this.listenCropMouseMove)
                        document.addEventListener('mouseup', this.ListenCropMouseUpOrLeave)
                        break
                    case 'CROP-SURE':
                        if (!this.cropLocation) {
                            this.plugins.msgError('请先框选图像区域')
                            return
                        }
                        this.loading = true
                        setTimeout(async () => {
                            await this.drawContent()
                            const [x, y, ex, ey] = this.cropLocation
                            var canvas = this.$refs['image-board']
                            var tmpCanvas = document.createElement('canvas');
                            tmpCanvas.width = ex - x
                            tmpCanvas.height = ey - y
                            var tmpCtx = tmpCanvas.getContext('2d');
                            tmpCtx.drawImage(this.imageData, x, y, ex - x, ey - y, 0, 0, ex - x, ey - y)
                            this.imageData = await this.getImageFromBase64(tmpCanvas.toDataURL("image/png"))
                            this.resetCanvasBlock()
                            await this.drawContent()
                            this.cropLocation = undefined
                            this.loading = false
                        }, 50)
                        break
                    case 'CROP-CANCEL':
                        //取消裁剪
                        this.btnActiveMark = undefined
                        await this.drawContent()
                        break
                    case 'PASSPORT-IMAGE-COUNT':
                    case 'PASSPORT-PAPER-TYPE':
                        this.childActiveMark = mark
                        break
                    case 'PASSPORT-CANCEL':
                        this.imageData = this.passportImageCache
                        await this.drawContent()
                        break
                    case 'PASSPORT-CLOSE':
                        this.btnActiveMark = undefined
                        break
                    case 'PASSPORT-START':
                        this.loading = true
                        setTimeout(async () => {
                            const { paperwh, imgInchs, rowPassportCount, colPassportCount, passportBoxWidth, passportBoxHeight } = this.calcPassportPaperAttr()
                            const container = document.getElementById('container')//获取父框宽高
                            const rate = this.canvasBlock.rw / this.canvasBlock.w //原相片的真实像素比
                            const canvasHeight = Math.floor(container.offsetHeight * 0.95)
                            const canvasWidth = Math.floor(canvasHeight * paperwh[0] / paperwh[1])
                            const imageHeight = Math.floor(canvasHeight * rate)
                            const imageWidth = Math.floor(canvasWidth * rate)
                            const unitPx = imageHeight / paperwh[1] //每厘米多少像素
                            const passportWidth = Math.floor(imgInchs[0] * unitPx)
                            const passportHeight = Math.floor(imgInchs[1] * unitPx)
                            var tmpCanvas = document.createElement('canvas');//临时画板
                            tmpCanvas.width = imageWidth
                            tmpCanvas.height = imageHeight
                            var tmpCtx = tmpCanvas.getContext('2d')
                            tmpCtx.fillStyle = 'white';
                            tmpCtx.fillRect(0, 0, imageWidth, imageHeight);
                            let passportStartX = Math.floor((this.passportRowPageBorder + this.passportBorder) * unitPx)
                            let passportStartY = Math.floor((this.passportColPageBorder + this.passportBorder) * unitPx)
                            let printCount = 0
                            for (let c = 0; c < colPassportCount; c++) {
                                for (let r = 0; r < rowPassportCount; r++) {
                                    tmpCtx.drawImage(this.passportImageCache, passportStartX, passportStartY, passportWidth, passportHeight);
                                    printCount++
                                    if (r < rowPassportCount - 1) {
                                        passportStartX += Math.floor(passportBoxWidth * unitPx)
                                    } else {
                                        passportStartX = Math.floor((this.passportRowPageBorder + this.passportBorder) * unitPx)
                                    }
                                    if (printCount >= this.passportCount) {
                                        break
                                    }
                                }
                                if (printCount >= this.passportCount) {
                                    break
                                }
                                passportStartY += Math.floor(passportBoxHeight * unitPx)
                            }
                            this.imageData = await this.getImageFromBase64(tmpCanvas.toDataURL("image/png"))
                            await this.drawContent()
                            this.loading = false
                        }, 50)
                        break
                    default:
                        break
                }
            },
            handleUserBackgroundClick(color) {
                this.passportBGColor = color
            },
            handlePassportPaperChange() {
                const attr = this.calcPassportPaperAttr()
                if (!attr) return
                this.passportCount = attr.passportCount
            },
            handleResolutionInput(m, v) {
                const rate = this.canvasBlock.w / this.canvasBlock.h
                if (m == 'w') {
                    //w改变，同步获取h
                    this.resolutionForm.h = Math.floor(v / rate)
                } else {
                    //h改变，同步获取w
                    this.resolutionForm.w = Math.floor(v * rate)
                }
            },
            handleEditResolution() {
                //重设分辨率
                this.loading = true
                setTimeout(async () => {
                    var tmpCanvas = document.createElement('canvas');//临时画板
                    tmpCanvas.width = this.resolutionForm.w
                    tmpCanvas.height = this.resolutionForm.h
                    var tmpCtx = tmpCanvas.getContext('2d')
                    tmpCtx.drawImage(this.imageData, 0, 0, this.resolutionForm.w, this.resolutionForm.h);
                    this.imageData = await this.getImageFromBase64(tmpCanvas.toDataURL("image/png"))
                    await this.drawContent()
                    this.plugins.msgSuccess('分辨率调整成功')
                    this.showResolution = false
                    this.loading = false
                }, 50)
            },
            handlePrint(preview) {
                //preview是true,预览打印，弹出预览框体
                this.printerForm.preview = preview
                window.$.sendIpc('main-pad-print', this.printerForm)
                if (!preview) this.showPrintPad = false
            },
            //保存当前图像为历史，在操作之前调用
            async saveImageDataHistory() {
                const canvas = this.$refs['image-board']
                const preImage = await this.getImageFromBase64(canvas.toDataURL("image/png"))
                if (this.imageDataHistory.length >= 10) {
                    delete this.imageDataHistory[0]
                    this.imageDataHistory = this.imageDataHistory.filter(e => e != null)
                }
                this.imageDataHistory.push(preImage)
            },
            //恢复历史
            async renderLastImageDataHistory() {
                if (!this.imageDataHistory.length) return
                this.imageData = this.imageDataHistory[this.imageDataHistory.length - 1]
                delete this.imageDataHistory[this.imageDataHistory.length - 1]
                this.imageDataHistory = this.imageDataHistory.filter(e => e != null)
                await this.drawContent()
            }
        }
    })
</script>

</html>